﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using CKS.PLC.Core.Cache;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Infrastructure;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP71
{
    /// <summary>
    /// 动作编号-1\3
    ///  钎焊炉开始加热
    /// </summary>
    public class DB1200_Work01Action : PLCAction
    {
        
        public DB1200_Work01Action(DecodeValue _value) : base(_value)
        {
           
        }
        public override void Execute()
        {
            var replayDB = 1200;
            var replayAction = Value.Position.ActionId;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetReplyPosition(replayDB, replayAction, 0);
         
            if (result == 1)
            {
                /*
                 创建热处理记录表 cks_heat_treatment
                 料架信息 开始时间 结束时间 状态 1开始 10完成 ， 创建时间
                 创建钎焊炉加热记录表
                 */

                var locationId = Value.Position.LocationId;
                var model = conn.Select<CksBrazingRecord>()
                    .Where(a=>a.LocationId == locationId)
                    .OrderByDescending(a => a.Id).First();

                if (model == null || model.Status == 10)
                {
                    string dayCacheKey = $"Brazing{DateTime.Now.ToString("yyMMdd")}";
                    var nextSeriaNumber = ServiceCommon.GetNextSerialNumber(dayCacheKey);
                    string nextNo = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";

                    var time = DateTime.Now;
                    model = new CksBrazingRecord()
                    {
                        LocationId = locationId,   
                        BatchNo = nextNo,
                        CreatedTime = time,
                        StartTime = time,
                        CurveNo = Value.GetLinkData(1).ToInt(),
                        SetTemperature = Value.GetLinkData(2).ToDecimal(),
                        MaterialRackNo = Value.GetLinkData(3).ToInt(),
                        VacuumDegree = Value.GetLinkData(4).ToDecimal(),
                        ElectricCabinetPower = Value.GetLinkData(5).ToDecimal(),
                        HeatingCabinetPower = Value.GetLinkData(6).ToDecimal(),
                        FurnaceNo = Value.GetLinkData(7).ToInt(),
                        Status = 1
                    };
                    conn.Insert(model).ExecuteAffrows();
                    //查询料架信息
                    var shelfCells = conn.Select<CksShelfForFixture>().Where(a => a.ShelfId == model.FurnaceNo).ToList();
                    SaveProductInfo(model, shelfCells);
                }

                



                EventBus.AddLog("OP71钎焊炉开始加热");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
               
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP71钎焊炉开始加热信号-重置");
            }
        }

        private void SaveProductInfo(CksBrazingRecord main,List<CksShelfForFixture> cells)
        {
            string intime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            foreach (var item in cells)
            {
                if(item.FixtureId>0)
                {
                    //架子上的夹具号大于0说明存放了夹具，查询夹具上绑定的条码信息
                    var fixture =conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == item.FixtureId).First();
                    if(fixture == null)
                    {
                        continue;
                    }

                    //码不为空存入OP90_Data表
                    var vt =conn.Select<CksVirtualTable>().Where(a => a.TableName == "OP71_Data").First();
                    var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
                    var columns = columnQuery.ToList();
                    var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);
                    var dict = new Dictionary<string, object>();
                    dict["CoverCode"] = fixture.CoverCode;
                    dict["FixtureNo"] = fixture.FixtureId;
                    dict["InTime"] = intime;
                    dict["FurnaceNo"] = main.FurnaceNo.ToString();
                    dict["CurveNo"] = main.CurveNo.ToString();
                    dict["SetTemperature"] = main.SetTemperature.ToString();
                    dict["MaterialRackNo"] = main.MaterialRackNo.ToString();
                    dict["VacuumDegree"] = main.VacuumDegree.ToString();
                    dict["ElectricCabinetPower"] = main.ElectricCabinetPower.ToString();
                    dict["HeatingCabinetPower"] = main.HeatingCabinetPower.ToString();
                    dict["BatchNo"] = main.BatchNo.ToString();

                    dict["CreatedTime"] = DateTime.Now;
                    dict["Nullity"] = false;
                    dict["IsDeleted"] = false;
                    object obj =table.CreateInstance(dict);
                    dict["Id"] = conn.Insert<object>().AsType(table.Type).AppendData(obj).ExecuteIdentity(); //保存到动态表
                   

                }
            }
        }
    }
}
